"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

exports.__esModule = true;
exports.useEventListener = void 0;

var React = _interopRequireWildcard(require("react"));

var isActionSupported = function isActionSupported(element, method) {
  return element ? !!element[method] : false;
};

var useEventListener = function useEventListener(options) {
  var capture = options.capture,
      listener = options.listener,
      type = options.type,
      target = options.target,
      targetRef = options.targetRef;
  var latestListener = React.useRef(listener);
  latestListener.current = listener;
  var eventHandler = React.useCallback(function (event) {
    return latestListener.current(event);
  }, []);

  if (process.env.NODE_ENV !== 'production') {
    // This is fine to violate there conditional rule as environment variables will never change during component
    // lifecycle
    // eslint-disable-next-line react-hooks/rules-of-hooks
    React.useEffect(function () {
      if (typeof target !== 'undefined' && typeof targetRef !== 'undefined') {
        throw new Error('`target` and `targetRef` props are mutually exclusive, please use one of them.');
      }

      if (typeof target === 'undefined' && typeof targetRef === 'undefined') {
        throw new Error("`target` and `targetRef` props are `undefined`, it' required to use one of them.");
      }
    }, [target, targetRef]);
  }

  React.useEffect(function () {
    var element = typeof targetRef === 'undefined' ? target : targetRef.current;

    if (isActionSupported(element, 'addEventListener')) {
      element.addEventListener(type, eventHandler, capture);
    } else if (process.env.NODE_ENV !== 'production') {
      throw new Error('@fluentui/react-component-event-listener: Passed `element` is not valid or does not support `addEventListener()` method.');
    }

    return function () {
      if (isActionSupported(element, 'removeEventListener')) {
        element.removeEventListener(type, eventHandler, capture);
      } else if (process.env.NODE_ENV !== 'production') {
        throw new Error('@fluentui/react-component-event-listener: Passed `element` is not valid or does not support `removeEventListener()` method.');
      }
    };
  }, [capture, eventHandler, target, targetRef, type]);
};

exports.useEventListener = useEventListener;
//# sourceMappingURL=useEventListener.js.map
